<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\MiniAppController;
use App\Models\SubscribeMessageAccept;
use App\Models\MessageTemplate;
use App\Models\SubscribeMessage;
use App\Models\Admin;

use App\Http\Services\SubscribeMessageService;

use App\Repositories\SubscribeMessageAcceptRepository;
use App\Repositories\MessageTemplateRepository;

use Exception;
use Illuminate\Support\Facades\Log;

/**
 * Class SubscribeController
 * @package
 */
class SubscribeController extends MiniAppController
{

    /**
     * @var
     */
    private $templateRep;
    private $acceptRep;

    public function __construct(
        MessageTemplateRepository $templateRep,
        SubscribeMessageAcceptRepository $acceptRep
    )
    {
        parent::__construct();
        $this->templateRep = $templateRep;
        $this->acceptRep = $acceptRep;
    }
    /**
     * 获取模板列表，用于小程序活动授权
     *
     * @param Request $request
     * @return Response
     *
     */
    public function templates()
    {
        $request = request();
        $templateType = array_filter(explode(",", $request->type));

        $SMTR = new MessageTemplateRepository();
        $data = $SMTR->list($templateType);
        $templateIds = [];

        foreach ($data as $item) {
            $templateIds[] = $item->wx_template_id;
        }

        return $this->apiResponse->success($templateIds);
    }

    /**
     * 保存活动消息授权
     *
     * @param Request $request
     *
     * @return Response
     */
    public function accept()
    {
        $activityId = request()->input('object_id', null);
        if (is_null($activityId)) {
            return $this->apiResponse->error('activity_id不可以为空', 411);
        }

        $accept = request()->input('accept', null);
        if (is_null($accept)) {
            return $this->apiResponse->error('accept不正确', 419);
        }
        $accept = json_decode($accept, true);
        $templateTypes = array_filter(explode(",", request()->type));
        $SMAR = new SubscribeMessageAcceptRepository();
        $SMTR = new MessageTemplateRepository();

        foreach ($accept as $WxTemplateId => $rs) {
            if ($rs === 'accept') {
                foreach ($templateTypes as $tk => $tv) {
                    $template = $SMTR->fromWxTemplate($WxTemplateId, intval($tv));
                    if (!$template) {
                        continue;
                    }
                    $SMAR->add(
                        intval(request()->get("wechat_admin_id")),
                        $template->id,
                        $activityId,
                        MessageTemplate::getModule($template['type']),
                        $clientVersion === MINI_APP_VERSION_DEVELOP ? SubscribeMessageAccept::STATUS_DEVELOP : SubscribeMessageAccept::STATUS_ENABLE
                    );
                }
            }
        }
        return $this->apiResponse->success([]);
    }

    /**
     * 发送消息模板
     * @param Request $request
     *
     * @return Response
     * @throws Exception
     */
    public function send()
    {
        $wechat_admin_id = request()->get("wechat_admin_id");
        $contactIds = Admin::whereNotNull("open_id")->distinct('open_id')->whereNotIn("open_id", [""])->pluck("id")->toArray();
        try {
            $SMS = new SubscribeMessageService();
            $SMS->addMessageBatch(
                MessageTemplate::TYPE_HOME_VISIT_TAB,
                $wechat_admin_id,
                $contactIds,
                [
                    "name" => "taoshuanghu",
                    // "step" => "33333",
                    "title" => "33333",
                    "time" => "2012-08-01",
                    "status" => "进行中",
                ],
                'pages/index/index',
                128,
            );

        } catch (Exception $e) {
            return $this->apiResponse->error('发送失败', 400);
        }
        return $this->apiResponse->success([]);
    }

}
